package com.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.domain.Folder;
import com.ssm.domain.SysFile;
import com.ssm.service.IFolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 文件夹控制类
 */
@Controller
@RequestMapping("/folder")
public class FolderController {

    @Autowired
    private IFolderService folderService;

    @RequestMapping("/addFileToFolder.do")
    public String addFileToFolder(@RequestParam(name = "folderId", required = true) String folderId,
                                @RequestParam(name = "ids", required = true) String[] fileIds) throws Exception {
        folderService.addFileToFolder(folderId, fileIds);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findFolderByIdAndAllFile.do")
    public ModelAndView findFolderByIdAndAllFile(@RequestParam(name="id",required = true) String folderId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Folder folder = folderService.findById(folderId);
        List<SysFile> otherFiles = folderService.findOtherFiles(folderId);
        mv.addObject("folder",folder);
        mv.addObject("sysFileList",otherFiles);
        mv.setViewName("folder-file-add");
        return mv;
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String folderId) throws Exception {
        ModelAndView mv = new ModelAndView();
        Folder folder = folderService.findById(folderId);
        mv.addObject("folder",folder);
        mv.setViewName("folder-show");
        return mv;
    }

    @RequestMapping("/save.do")
    public String save(Folder folder) throws Exception {
        folderService.save(folder);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(name="page",required = true, defaultValue = "1") Integer page,
                                @RequestParam(name="size",required = true, defaultValue = "5") Integer size)
            throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Folder> folderList = folderService.findAll(page,size);
        PageInfo pageInfo = new PageInfo(folderList);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("folder-list");
        return mv;
    }

    @RequestMapping("/deleteFolder.do")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String deleteFolder(@RequestParam(name="id", required = true)String folderId) throws Exception {
        folderService.deleteFolder(folderId);
        return "redirect:findAll.do";
    }
}
